package dvsdk.client;

import dvsdk.db.BeanBase;
import dvsdk.GlobalConfig;
import dvsdk.util.ExUtil;
import dvsdk.form.FEditPlace;
import dvsdk.form.JImageFileChooser;
import dvsdk.form.SearchBoxModel;
import dvsdk.util.Util;
import java.awt.Component;
import java.awt.Window;
import java.awt.event.MouseAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import mulis.photoviewer.GraphBtn;

/**
 *
 * @author Ivan
 */
public class MulisFrame extends JFrame {

    protected Window ownerWindow = null;
    //protected IFrameCore frameCore = null;
    protected JPanel photopanel = null;
    private boolean mod = false;
    protected JButton closeButton = null;
    protected JButton saveButton = null;
    protected JTextArea privComment = null;
    private BeanBase binBase = null;
    private JTextField photos = null;
    private JComboBox agentInfo = null;
    private JComboBox streetList = null;
    public MulisTableModel model = null;
    private JTable table = null;

    public MulisFrame() {
        photos = new JTextField();
        photos.setName("photos");
        //photos.setText("Фото");
        photos.setVisible(false);
        photos.getAccessibleContext().setAccessibleName("Фото");
        photos.getAccessibleContext().setAccessibleDescription("50");
        this.add(photos);
        
        
        addWindowListener(new java.awt.event.WindowAdapter() {

            @Override
            public void windowClosed(java.awt.event.WindowEvent evt) {
                GlobalConfig.getCore().setEnable();
                if (ownerWindow != null) {
                    ownerWindow.setEnabled(true);
                }
            }
        });
    }
/*
    public MulisFrame(IFrameCore core) {
        this();
        this.frameCore = core;
    }*/

    public MulisFrame(Window ownerWindow) {
        this();
        this.ownerWindow = ownerWindow;
    }
    
    public final void postInitButtons(JButton closeButton, JButton saveButton) {
        this.setCloseButton(closeButton);
        this.setSaveButton(saveButton);
    }
    
    public final void postInit(JPanel photoPanel, JTextArea privComment, JScrollPane scrollPane, JTable table, JComboBox i_agent, JComboBox streetList) {
        this.setLocationRelativeTo(null);
        this.setPhotopanel(photoPanel);
        scrollPane.getVerticalScrollBar().setUnitIncrement(80);
        this.setAlwaysOnTop(true);
        this.setTable(table);
        this.setAgentInfo(i_agent);
        this.setPrivComment(privComment);
        this.setStreetList(streetList);
        
        table.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                if (evt.getClickCount() == 2) {
                    editLocation();
                }
            }
        });

        addWindowListener(new java.awt.event.WindowAdapter() {

            @Override
            public void windowClosed(java.awt.event.WindowEvent evt) {
                Component[] com = getPhotopanel().getComponents();
                for (Component component : com) {
                    if (component instanceof GraphBtn) {
                        ((GraphBtn) component).setImage(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB));
                    }
                }
            }
        });
        Util.fillJFrameJComboBox(this);
        initLocationTable();
    }
    
    private void initLocationTable() {
        MulisTableModel mtm = new MulisTableModel();
        mtm.setNumRows(0);
        mtm.addColumn("Тип");
        mtm.addColumn("Название");
        mtm.addColumn("Комментарий");
        table.setModel(mtm);
        setModel(mtm);
    }

    public JTextArea getPrivComment() {
        return privComment;
    }

    public void setPrivComment(JTextArea privComment) {
        this.privComment = privComment;
    }

    public JButton getSaveButton() {
        return saveButton;
    }

    public void setSaveButton(JButton saveButton) {
        this.saveButton = saveButton;
    }

    public MulisTableModel getModel() {
        return model;
    }

    public void setModel(MulisTableModel model) {
        this.model = model;
    }

    public JTable getTable() {
        return table;
    }

    public void setTable(JTable table) {
        this.table = table;
    }

    public BeanBase getBinBase() {
        return binBase;
    }

    public void setBinBase(BeanBase binBase) {
        this.binBase = binBase;
    }

    public Window getOwnerWindow() {
        return ownerWindow;
    }

    public void setOwnerWindow(Window ownerWindow) {
        this.ownerWindow = ownerWindow;
    }

    public JPanel getPhotopanel() {
        return photopanel;
    }

    public void setPhotopanel(JPanel photopanel) {
        this.photopanel = photopanel;
    }

    public JComboBox getAgentInfo() {
        return agentInfo;
    }

    public void setAgentInfo(JComboBox agentInfo) {
        this.agentInfo = agentInfo;
        this.agentInfo.setEnabled(false);
        /*
        this.agentInfo.addItemListener(new java.awt.event.ItemListener() {
            @Override
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                //getAgentPhone().setText(Lang.findUserContactByIDA( ((MulisComboBoxModelUsers)getAgentInfo().getModel()).getCurrentElement(getAgentInfo().getSelectedIndex()) ));
            }
        });*/
        // TODO: Дополнительная информация про агента
        /*
        this.agentInfo.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            @Override
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                if (getAgentInfo().getModel() instanceof MulisComboBoxModelUsers)
                    getAgentPhone().setText(Lang.findUserContactByIDA( ((MulisComboBoxModelUsers)getAgentInfo().getModel()).getCurrentElement(getAgentInfo().getSelectedIndex()) ));
            }
        });*/
        
    }

    public boolean isMod() {
        return mod;
    }

    public void setMod(boolean mod) {
        this.mod = mod;
    }

    public String getID() {
        return this.getAccessibleContext().getAccessibleDescription();
    }

    public void setID(String id) {
        this.getAccessibleContext().setAccessibleDescription(id);
    }

    public boolean save() {
        List<BufferedImage> images = getImages();
        if (images.size() > 0) {
            photos.setText("local-" + images.size());
        } else {
            photos.setText("");
        }
        if (!ExUtil.grab(GlobalConfig.getCore().getBase(getName()), this)) {
            return false;
        }
        Util.saveImagesToDir(images, getID(), getName());
        images = null;
        return true;
    }

    public void saveAndExit() {
        if (this.save()) {
            if (isMod()) GlobalConfig.getCore().refreshCurrentRow();
            else GlobalConfig.getCore().refreshCurrentTable(true);
            this.dispose();
        }
    }

    @Override
    public void setDefaultCloseOperation(int operation) {
        super.setDefaultCloseOperation(operation);
        photopanel = null;
    }

    public List<BufferedImage> getImages() {
        List<BufferedImage> ret = new ArrayList<BufferedImage>();
        Component[] components = photopanel.getComponents();
        for (Component component : components) {
            if (component instanceof GraphBtn) {
                ret.add(((GraphBtn) component).getImage());
            }
        }
        return ret;
    }

    public JButton getCloseButton() {
        return closeButton;
    }

    public void setCloseButton(JButton closeButton) {
        this.closeButton = closeButton;
        if (GlobalConfig.DEBUG==0) this.closeButton.setVisible(false);
    }

    public JComboBox getStreetList() {
        return streetList;
    }

    public void setStreetList(JComboBox streetList) {
        this.streetList = streetList;
    }
    
    @Override
    public void setVisible(boolean b) {
        super.setVisible(b);
        GlobalConfig.getCore().setDisable();
        if (this.getAccessibleContext().getAccessibleDescription() == null) {
            this.getAccessibleContext().setAccessibleDescription(Integer.toString(ExUtil.count(GlobalConfig.getCore().getBase(this.getName()), this.getName(), null) + 1));
        }
        if (GlobalConfig.DEBUG > 0) {
            System.out.println("ID: " + this.getAccessibleContext().getAccessibleDescription());
        }
        
        SearchBoxModel sbm = new SearchBoxModel(streetList);
        //set the model on the combobox
        streetList.setModel(sbm);
        //set the model as the item listener also
        streetList.addItemListener(sbm);
        
        if (this.agentInfo.getModel() instanceof MulisComboBoxModelUsers)
            for (int i = 0; i < this.agentInfo.getModel().getSize(); i++) {
                if (binBase==null) break;
                if (((MulisComboBoxModelUsers)this.agentInfo.getModel()).getCurrentElement(i).toString().equals(binBase.getIdr())) {
                    this.agentInfo.setSelectedIndex(i);
                    break;
                }
            }
        
        if (isMod()) {
            closeButton.setVisible(false);
            if (!binBase.getIdr().equals(GlobalConfig.AGENT_INN) || (!binBase.getIda().equals(GlobalConfig.MASTER_INN))) {
                saveButton.setVisible(false);
                if (!GlobalConfig.MASTER_INN.equals(binBase.getIda())) privComment.setVisible(false);
            }
            if (binBase.getIda().equals(GlobalConfig.MASTER_INN) && GlobalConfig.IS_MASTER) saveButton.setVisible(true);
            List<File> images = Util.loadImagesFromDir(getID(), binBase.getIda(), getName());
            if (images != null) {
                for (Iterator<File> it = images.iterator(); it.hasNext();) {
                    File file = it.next();
                    addImgToPhotoPanel(file);
                }
            }
            images = null;
        }
        if (GlobalConfig.IS_MASTER) {
            getAgentInfo().setEnabled(true);
        }
    }

    public void addImgToPhotoPanel(String patch) {
        addImgToPhotoPanel(new File(patch));
    }

    public void addImgToPhotoPanel(File patch) {
        try {
            GraphBtn btn = new GraphBtn(this);
            btn.setImage(Util.resizeImage(ImageIO.read(patch),
                    GlobalConfig.THUMBINAL_WIDTH, GlobalConfig.THUMBINAL_HEIGHT));
            //images.add(btn);
            photopanel.add(btn);
            photopanel.repaint();
            btn = null;
        } catch (Exception ex) {
            if (GlobalConfig.DEBUG > 0) {
                System.err.println(ex.getLocalizedMessage());
            }
            if (GlobalConfig.DEBUG > 1) {
                ex.printStackTrace();
            }
        }
    }

    public void addImageToButton() {
        JImageFileChooser chooser = new JImageFileChooser(JImageFileChooser.lastFilePath);
        chooser.setMultiSelectionEnabled(true);
        if (chooser.showOpenDialog(this) == JImageFileChooser.APPROVE_OPTION) {
            JImageFileChooser.lastFilePath = chooser.getSelectedFile().getPath();
            File[] files = chooser.getSelectedFiles();
            for (int i = 0; i < files.length; i++) {
                try {
                    addImgToPhotoPanel(files[i]);
                    files[i] = null;
                } catch (Exception e) {
                    if (JOptionPane.showConfirmDialog(this, "Не могу загрузить "
                            + files[i] + "\nОшибка " + e.getLocalizedMessage()
                            + "\nПродолжить загружать другие изображения?",
                            "Ошибка", JOptionPane.ERROR_MESSAGE, JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
                        return;
                    }
                }
            }
            files = null;
        }
    }

    public void addLocation() {
        FEditPlace fep = new FEditPlace(this, true);

        fep.setTitle("Добавить ориентир");
        if (fep.execute()) {
            String[] d = new String[3];
            d[0] = fep.type;
            d[1] = fep.name;
            d[2] = fep.comment;
            model.addRow(d);

            //model.insertRow(0, d);
        }
    }

    public void deleteLocation() {
        int sel = table.getSelectedRow();
        if (model.getRowCount() > 0) {
            if ((sel >= 0) && (sel < model.getRowCount())) {
                if (JOptionPane.showConfirmDialog(this, "Удалить запись?", "Подтвердите",
                        JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
                    model.removeRow(sel);
                }
            }
        }

    }
    
    public void editLocation() {
        FEditPlace fep = new FEditPlace(this, true);

        int sel = table.getSelectedRow();
        if (model.getRowCount() > 0) {
            if ((sel >= 0) && (sel < model.getRowCount())) {
                if (fep.execute(model.getValueAt(sel, 0).toString(),
                        model.getValueAt(sel, 1).toString(),
                        model.getValueAt(sel, 2).toString())) {
                    model.setValueAt(fep.type, sel, 0);
                    model.setValueAt(fep.name, sel, 1);
                    model.setValueAt(fep.comment, sel, 2);
                }
            }
        }
    }
}
